package com.test.pass.test1;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.SocketChannel;
import java.util.Iterator;

public class NIOClient {
    SocketChannel client;
    Selector selector;
    ByteBuffer buffer;
    public NIOClient() throws IOException {
        client = SocketChannel.open(new InetSocketAddress("127.0.0.1",9800));
        selector = Selector.open();
        client.configureBlocking(false);
        client.register(selector,SelectionKey.OP_READ);
        buffer = ByteBuffer.allocate(5555);
        connect();
    }
    /*
     * 连接服务端，并且把传递过来的数据读取到缓冲区
     */
    public void connect() throws IOException {
        while (true) {
            if (selector.select()>0) {
                Iterator<SelectionKey> ikeys = selector.selectedKeys().iterator();
                while (ikeys.hasNext()) {
                    SelectionKey selectionKey = ikeys.next();
                    if (selectionKey.isReadable()) {
                        reads();
                    }
                    ikeys.remove();
                }
            }

        }

    }
    public void reads() throws IOException {
        buffer.clear();
        client.read(buffer);
        buffer.flip();
        System.out.println(new String(buffer.array() ,
                0 , buffer.limit() , "UTF-8"));
    }
    public static void main(String[] args) throws IOException {
        NIOClient client01 = new NIOClient();
    }
}
